/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "GET") {
  wx.showLoading({
    title: '加载中...',
  })
  return new Promise(function(resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        console.log("success");
        resolve(res.data)
      },
      fail: function(err) {
        reject(err)
        console.log("请求失败failed")
      },
      complete:function(){
        wx.hideLoading();
      }
    })
  });
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    icon: 'none'
  })
  return
}

function showSuccessToast(msg) {
  wx.showToast({
    title: msg,
  })
}

//多张图片上传
function uploadimg(data) {
  var that = this,
    i = data.i ? data.i : 0,//当前上传的哪张图片
    success = data.success ? data.success : 0,//上传成功的个数
    fail = data.fail ? data.fail : 0;//上传失败的个数
  wx.uploadFile({
    url: data.url,
    filePath: data.path[i],
    name: 'file',//这里根据自己的实际情况改
    formData: null,//这里是上传图片时一起上传的数据
    success: (resp) => {
      success++;//图片上传成功，图片上传成功的变量+1
      console.log(resp)
      console.log(i);
      //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
    },
    fail: (res) => {
      fail++;//图片上传失败，图片上传失败的变量+1
      console.log('fail:' + i + "fail:" + fail);
    },
    complete: () => {
      console.log(i);
      i++;//这个图片执行完上传后，开始上传下一张
      if (i == data.path.length) {   //当图片传完时，停止调用          
        console.log('执行完毕');
        console.log('成功：' + success + " 失败：" + fail);
      } else {//若图片还没有传完，则继续调用函数
        console.log(i);
        data.i = i;
        data.success = success;
        data.fail = fail;
        that.uploadimg(data);
      }

    }
  });
}
/**
 * 设置页面导航栏颜色
 */
function setBarColor() {
  var backgroundColor = wx.getStorageSync('backgroundColor');
  if (backgroundColor != '')
  {
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: backgroundColor,
    })
  }
}
module.exports = {
  request,
  showErrorToast,
  showSuccessToast,
  uploadimg,
  setBarColor
}